'use strict';

const { logger } = require('ee-core/log');
const axios = require('axios');
const date = require('../utils/date.js');
const { configService } = require('./config.js');
const { computerService } = require('../service/computer');

/**
 * 示例服务
 * @class
 */
class TicketService {

    ssoHost = configService.get("ssoHost");
    eap1Host = configService.get("eap1Host");
    mailHost = configService.get("mailHost");
    heartbeatID = null;//心跳ID
    userInfo = {};
    //登录eap1获取cookie
    async login(userName, password) {

        let hardinfo = "";//"0010000000%7CF01521A%7C7A46D0A9A022266B0805D36EDBE9C2F0C775560DA397D10D76B85F4795F9C1ABC39E21E9B9C5DAD9BB6745C4301F14ECA2C393DCA8817EE219736D635A7A740C221C59CF935E4BECE8CE2C4A2CD811CFCD71DEC108F9A0D6C518185256B2EB49061B6B0C183166B0D4E66935219D4930CFDFF30E8E888EADF466990CD136E8C786E925624FE936A6F4E2CE9F54466CE5C57AAF8CC500CFDA1BEC80C520F35DA29CE505F99EF079053D4C224838EA47FB185DB314681B8D3E9CC275E38C7AF1E9E303BCD68377C5024CB7940EC65794C6D1345ED3182CAECFBA0233C849873BB21A376C6AC19701E573888D4BCE8DFFA66319046B247FE416A3E81635B5CF66786821B57EA6F9040D5ECE7F2C0D9121BD";
        hardinfo = await computerService.getHardInfoToString();
        let curTime = date.format(new Date(), "yyyy-MM-dd HH:mm:ss")
        let service = `${this.eap1Host}/bws/system/xtgn/xtzy/zy1-query/bizFunction.open.bws` //'http://eap2.fdauto.com/eap/xtgn/xtsy/sy/sy.flow'
        const url = `${this.ssoHost}/ssoAuth/remoteLogin?submit1=true&cs=true&service=${service}&loginUrl=http%3A%2F%2Fwww.baidu.com&username=${userName}&password=${encodeURIComponent(password)}&loginStartTime=${curTime}&hardinfo=${hardinfo}`
        let result = {
            success: false,
            message: null
        }, location, cookie;
        //验证用户名密码并获取票据
        try {
            let res = await axios.get(url, {
                maxRedirects: 0,
            })
            // 定义正则表达式
            const regex = /<cas:msg\s+value=['"]([\s\S]*?)['"]\s*\/>/;
            const match = res.data.match(regex);
            if (match && match[1]) {
                const errorMessage = match[1].trim();
                result.message = errorMessage;
            } else {
                result.message = "登录失败!";
            }
            logger.error('登录失败:', result.message);
            return result;
        } catch (res) {
            //验证成功,302跳转
            result.success = true;
            location = res.response.headers.location
        }
        //到eap1消费票椐,获取cookie
        try {
            let res = await axios.get(location, {
                maxRedirects: 0,
            });

        } catch (res) {
            location = res.response.headers.location
            cookie = res.response.headers["set-cookie"][0].split(";")[0]
            result.cookie = cookie;
            this.saveUserInfo({
                id: userName,
                cookie: cookie,
                loginTime: new Date()
            })
            //开启心跳
            this.heartbeat();
            logger.info('登录成功,cookie:', result.cookie);
        }



        return result
    }

    //登录eap1获取cookie
    async getloginapi(userName, password) {

        let hardinfo = "" ;//"0010000000%7CF01521A%7C7A46D0A9A022266B0805D36EDBE9C2F0C775560DA397D10D76B85F4795F9C1ABC39E21E9B9C5DAD9BB6745C4301F14ECA2C393DCA8817EE219736D635A7A740C221C59CF935E4BECE8CE2C4A2CD811CFCD71DEC108F9A0D6C518185256B2EB49061B6B0C183166B0D4E66935219D4930CFDFF30E8E888EADF466990CD136E8C786E925624FE936A6F4E2CE9F54466CE5C57AAF8CC500CFDA1BEC80C520F35DA29CE505F99EF079053D4C224838EA47FB185DB314681B8D3E9CC275E38C7AF1E9E303BCD68377C5024CB7940EC65794C6D1345ED3182CAECFBA0233C849873BB21A376C6AC19701E573888D4BCE8DFFA66319046B247FE416A3E81635B5CF66786821B57EA6F9040D5ECE7F2C0D9121BD";
        hardinfo = await computerService.getHardInfoToString();
        let curTime = date.format(new Date(), "yyyy-MM-dd HH:mm:ss")
        let service = `${this.eap1Host}/bws/system/xtgn/xtzy/zy1-query/bizFunction.open.bws` //'http://eap2.fdauto.com/eap/xtgn/xtsy/sy/sy.flow'
        const url = `${this.ssoHost}/ssoAuth/remoteLogin?submit1=true&cs=true&service=${service}&loginUrl=http%3A%2F%2Fwww.baidu.com&username=${userName}&password=${password}&loginStartTime=${curTime}&hardinfo=${hardinfo}`
        return url
    }

    async logout() {
        this.userInfo = {};
        if (this.heartbeatID) {
            clearInterval(this.heartbeatID);
            this.heartbeatID = null;
        }

    }

    async loginMail() {
        let _this = this;
        let url = `${this.mailHost}/webmail/module/mail.do?method=getUnreadMailInfo`;
        let ticket = await this.getNewTicket(url);
        let loginResult, ssoCookie = [], mailCookie = [], location;
        try {

            let loginValidateUrl = `${this.ssoHost}/ssoAuth/loginValidate?ticket=${ticket}&service=${decodeURIComponent(url)}`
            loginResult = await axios.get(loginValidateUrl, {
                maxRedirects: 0,
                withCredentials: true
            })

        } catch (res) {
            logger.error('邮件登录失败1:', res);
            return {
                success: false,
                message: "邮件登录失败!" + res.message
            };
        }
        ssoCookie = this.splitCooike(loginResult.headers["set-cookie"])
        try {
            await jumpRequest(`${this.ssoHost}/ssoAuth/remoteLogin?service=${decodeURIComponent(url)}&loginUrl=${encodeURIComponent(this.eap1Host + "/bws/auth/login.jsp")}`)
            this.userInfo.mailCookie = mailCookie.join(";");
        } catch (res) {
            logger.error('邮件登录失败2:', res);
            return {
                success: false,
                message: "邮件登录失败!" + res.message
            };
        }

        return {
            success: true
        };
        //递归跳转请求
        async function jumpRequest(url) {
            let resCookie;
            if (url.startsWith(_this.ssoHost))
                resCookie = ssoCookie;
            else
                resCookie = mailCookie;

            try {
                let res = await axios.get(url, {
                    maxRedirects: 0,
                    headers: {
                        'Cookie': resCookie.join(";"),
                    }
                })
                return res;
            } catch (res) {
                if (res.status == 302) {
                    if (res.response.headers["set-cookie"] && res.response.headers["set-cookie"].length > 0) {
                        let newCookie = _this.splitCooike(res.response.headers["set-cookie"])
                        if (url.startsWith(_this.ssoHost))
                            ssoCookie = _this.mergeCookie(ssoCookie, newCookie);
                        else
                            mailCookie = _this.mergeCookie(mailCookie, newCookie);
                    }
                    //获取跳转地址
                    location = res.response.headers.location;
                    return jumpRequest(location);
                } else {
                    throw new Error("跳转失败!" + res.message);
                }

            }
        }
    }


    splitCooike(cookies) {
        let result = [];
        for (let i = 0; i < cookies.length; i++) {
            const element = cookies[i];
            if (element.includes(";")) {
                result.push(element.substring(0, element.indexOf(";")))
            } else
                result.push(element)
        }
        return result;
    }

    // 合并cookie
    mergeCookie(cookie1, cookie2) {
        let result = cookie1.slice();;
        for (let i = 0; i < cookie2.length; i++) {
            const item2 = cookie2[i];
            let find = "";
            let cooikeKey2 = item2.substring(0, item2.indexOf("="))
            for (let i = 0; i < result.length; i++) {
                const item = result[i];
                let cooikeKey1 = item.substring(0, item.indexOf("="))
                if (cooikeKey1 == cooikeKey2) {
                    find = true;
                    break;
                }
            }
            if (!find)
                result.push(item2);
        }
        return result;
    }

    //心跳,保持cookie不超时
    async heartbeat() {
        const url = `${this.eap1Host}/bws/system/xtgn/scj/eapscj-query!scj/bizFunction.open.bws?__enableput=false`
        const cookie = this.userInfo.cookie;
        this.heartbeatID = setInterval(() => {
            axios.get(url, {
                headers: {
                    'Cookie': cookie
                }
            }).then(res => {
                if (res.status != 200) {
                    logger.error('心跳失败:', res);
                }
                let curTime = date.format(new Date(), "yyyy-MM-dd HH:mm:ss")
                console.log(`[${curTime}] 心跳`, res.data.trim());
            }).catch(err => {
                logger.error('心跳失败:', err);
            })
        }, 1000 * 60 * 10);//10分钟一次  
    }
    /**
     * 获取Eap5兼容票椐
     */
    async getNewTicket(service) {
        let cookie = this.userInfo.cookie;
        //取eap5的票据时要用这个通用的service:http://eap2.fdauto.com/eap/rlzy/rsgl/ygda/ygda.flow,用这个通用service取的得票据要加fromEap2=true
        let res = await axios.get(`${this.eap1Host}/bws/uploadSysFile.fetchTicket.bws?proxyService=${encodeURIComponent(service)}`, {
            //maxRedirects: 0,
            headers: {
                'Cookie': cookie
            }
        });
        const regex = /<proxyTicket>(.*?)<\/proxyTicket>/;

        const match = res.data.match(regex);

        if (match && match[1]) {
            const proxyTicket = match[1];
            return proxyTicket;
        }
        return null;
    }
    async getUserInfo() {
        return this.userInfo
    }
    async saveUserInfo(userInfo) {
        this.userInfo = userInfo;
    }
}
TicketService.toString = () => '[class TicketService]';

module.exports = {
    TicketService,
    ticketService: new TicketService()
};